let db = require("../db/db")

let handle = async function (action, data, callback, login_info, req, res) {
	let result;
	switch (action) {
		case "getbyname":
			let name = data.name;
			let sql = "select * from sys_configer where name=? and is_deleted=0";
			result = await db.query(sql, [name]);
			return ({
				controls: JSON.parse("[" + result.rows[0].configer + "]"),
				data: JSON.parse("{\"configer\":" + (data.config_data ? data.config_data : "{}") + "}")
			});
			break;
		case "getforpage": //only for 页面CRUD编辑页
			//下面这些参数在页面CRUD用不到，在其他CRUD可能用到，因为CRUD前端是一个程序，所以都传过来
			let datamodel = data.datamodel;
			let page_id = data.page_id;
			let fieldname = data.fieldname;
			let id = data.row.id;

			if (!data.row || !data.row.page_type_id) {
				return ({ controls: [], data: {} });
			}
			let page_type_id = data.row.page_type_id;
			let p_sql = "select * from sys_page_type where id=? and is_deleted=0";
			result = await db.query(p_sql, [page_type_id]);
			let property_set = JSON.parse(result.rows[0].property_set);
			if (property_set && property_set.configer) {
				let configer_name = property_set.configer;
				p_sql = "select * from sys_configer where name=? and is_deleted=0";
				result = await db.query(p_sql, [configer_name]);
				if (result.rows.length == 0) { return (Error('没有找到配置器:' + configer_name)); }
				return ({
					controls: JSON.parse("[" + result.rows[0].configer + "]"),
					data: JSON.parse("{\"configer\":" + (data.config_data ? data.config_data : "{}") + "}")
				});
			}
			else {
				return ({
					controls: [],
					data: JSON.parse(data.config_data)
				});
			}
			break;
		default:
			return (Error('未知的action:' + action));
	}
}

module.exports = { handle };